package com.pcbly.web.components.utils.fileupload;

import java.io.ByteArrayOutputStream;

public class PlainURLEncoder {
	private static char[] tab = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	
	public static String encode(String s) {
        try {
            if (s == null || s.equals(""))
                return "";
        	String tmpStr = "";
        	byte tmpByte[] = s.getBytes();
        	for(int i=0;i < tmpByte.length;i++){
        		
        		tmpStr += "" + tab[0x0f & (tmpByte[i] >> 4)] + tab[ 0x0F & tmpByte[i]];
        		
        	}
        	
        	return  tmpStr;
        }
        catch (Exception e) {
        	e.printStackTrace();
            return s;
        }
    }

	public static String decode(String s) {
        try {
            if (s == null || s.equals(""))
                return "";

            ByteArrayOutputStream bytess = new ByteArrayOutputStream();
            

        	byte tmpByte[] = s.toUpperCase().getBytes();
        	for(int i=0;i < tmpByte.length /2 ;i++){
        		

        		tmpByte[i*2] = pocb(tmpByte[i*2]);
        		tmpByte[i*2+1] = pocb(tmpByte[i*2+1]);

        		
        		bytess.write((tmpByte[i*2] <<4)|(tmpByte[i*2+1]));
        	}
            
        	bytess.flush();
        	
            return  new String(bytess.toByteArray());
        }
        catch (Exception e) {
            return s;
        }
    }
	
	private static byte pocb(byte b){
		
		if(b>57){
			b-=55;
		}else{
			b-=48;
		}
		
		return b;
		
	}
}
